<?php
// +----------------------------------------------------------------------
// | duoduojie app system
// +----------------------------------------------------------------------
// | Copyright (c) 2017 duoduojie app All rights reserved.
// +----------------------------------------------------------------------
// | Author: Gooe <zqscjj@163.com> QQ:81009953
// +----------------------------------------------------------------------
namespace app\api\controller;
use think\Controller;
use app\common\controller\Api;
/**
 * 助手导单
 * @author zqs
 *
 */
class Import extends Api
{
    /**
     * 加密验证数据合法性
     */
    public function initialize()
    {
        parent::initialize();
        $t = input('t');
        $sign = input('sign');
        $key = '445af7aebf2b2f85293b57c2778a50c5';
        $rsign = md5($t.'|'.$key);
        if ($rsign!=$sign){
            exit('签名错误');
        }
    }
    /**
     * 订单明细-淘宝客推广 
     */
    public function tbktg($order_third=0)
    {
        $data = file_get_contents('php://input');trace($data);
        //新格式，多了一个技术服务费比例，在佣金金额之后,第三方订单没有加
        //$data = '["2018-06-20 21:35:05","2018-06-20 20:34:32","这是一个测试的砍价订单2","39543268499","淘信佳园","淘信佳园","1","11","订单结算","淘宝","20 %","100.00 %","1000","0.08","0","10","2018-06-20 20:55:32","8.00 %","0","0.00 %","0","-","无线","--","131844283696974659","男装","42520286","朵朵街","233494528","朵朵街app"]';
        $data = json_decode($data,true);
        if (!is_array($data)) exit('error');
        //查下本地订单记录 分配给用户
        $trade_no = $data[25];
        if ($order_third==1){
            $trade_no = $data[24];
        }
        if (empty($trade_no)) exit('error');
        $click_time = $data[1];
        $item_id = $data[3];
        //先查支付记录,获取用户uid
        $uid = 0;
        $order_local = db('OrderLocal')->where('orderid',$trade_no)->find();
        if ($order_local){
            $uid = $order_local['uid'];
        }
        //订单后6位识别uid
        $tb_order6 = substr($trade_no, -6);
        if (empty($uid)){
            $uid = db('User')->where('tb_order6',$tb_order6)->order('uid asc')->value('uid');
            if (empty($uid)) $uid = 0;
        }
        //数据转换--begin
        if ($order_third==0){
            $keys = [
                'create_time','click_time','title','item_id','zg_ww','shop_tile','item_num','item_price','order_status','order_type','income_rate',
                'share_rate','pay_fee','xgyg','js_price','ygsr','js_time','rj_rate','rj_price','js_fuwu_rate','bt_rate','bt_price','bt_type','cjpt','third_come',
                'trade_no','cate_title','site_id','site_name','adzone_id','adzone_name'
            ];
        }else{
            $keys = [
                'create_time','click_time','title','item_id','zg_ww','shop_tile','item_num','item_price','order_status','order_type','income_rate',
                'share_rate','pay_fee','xgyg','js_price','ygsr','js_time','rj_rate','rj_price','bt_rate','bt_price','bt_type','cjpt','third_come',
                'trade_no','cate_title','site_id','site_name','adzone_id','adzone_name'
            ];
        }
        //数据类型转换
        $updata = array_combine($keys, $data);
        $updata['uid'] = $uid;
        $updata['income_rate'] = floatval($updata['income_rate']);
        $updata['share_rate'] = floatval($updata['share_rate']);
        $updata['rj_rate'] = floatval($updata['rj_rate']);
        $updata['bt_rate'] = floatval($updata['bt_rate']);
        $updata['order_type'] = $updata['order_type']=='天猫'?1:0;
        if (empty($updata['js_time'])) unset($updata['js_time']);
        //订单文字2int
        $orderst_text2int = array_flip(config('site.orderst_text'));
        $updata['order_status'] = $orderst_text2int[$updata['order_status']];
        $updata['order_third'] = $order_third;
        //数据转换--end
        
        //查找是否存在
        $order = db('Orders')->where(['trade_no'=>$trade_no,'click_time'=>$click_time,'item_id'=>$item_id])->find();
        //如果订单被删除则不处理,add
        if ($order && $order['status']!=1){
            trace('订单被删除');
            exit('ok');
        }
        //查询宝贝信息，存入图片
        $options = [
            'appkey' => $this->tk_appkey,
            'appsecret' => $this->tk_appsecret,
            'num_iids' => (string)$updata['item_id']
        ];
        $tk = new \ddj\Tk($options);
        $item_info = $tk->info_get();
        if (isset($item_info['results'])){
            $updata['pict_url'] = $item_info['results']['n_tbk_item']['pict_url'];
        }
        
        //拦截砍价订单
        $kanjia_info = false;
        if ($uid>0){
            //首次导入
            $kanjia_info = model('KanjiaGoods')->get(['uid'=>$uid,'item_id'=>$updata['item_id'],'status'=>3,'order_id'=>0]);
            if ($kanjia_info){
                $updata['is_kanjia'] = 1;//给订单标识
            }
        }
        //拦截免单订单
        $miandan_info = false;
        trace($uid);
        if ($uid>0){
            $miandan_info = model('MiandanOrder')->get(['uid'=>$uid,'item_id'=>$updata['item_id'],'is_used'=>0]);
            trace(['uid'=>$uid,'item_id'=>$updata['item_id'],'is_used'=>0]);
            trace($miandan_info);
            if ($miandan_info){
                $updata['is_miandan'] = 1;//给订单标识
            }
        }
        
        //dump($order['id']);dump($order_model);die;
        //判断订单状态 TODO：订单成功的问题？
        if ($updata['order_status']==1){//..如果是订单付款状态
            if (!$order){//..不存在则导入
                $order_id = db('Orders')->insertGetId($updata);
                //首次导入订单，绑定砍价
                if ($kanjia_info){
                    $kanjia_info->order_id = $order_id;
                    $kanjia_info->save();
                }elseif ($miandan_info){
                    $miandan_info->order_id = $order_id;
                    $miandan_info->save();
                }
            }
        }elseif ($updata['order_status']==3){//..失效订单
            if ($order){//..存在则改变订单状态
                unset($updata['uid']);//防止找回订单没浏览记录的情况
                db('Orders')->where('id',$order['id'])->update($updata);
            }else {//..反之导入
                $order_id = db('Orders')->insertGetId($updata);
                //首次导入订单，绑定砍价
                if ($kanjia_info){
                    $kanjia_info->order_id = $order_id;
                    $kanjia_info->save();
                }elseif ($miandan_info){
                    $miandan_info->order_id = $order_id;
                    $miandan_info->save();
                }
            }
        }elseif ($updata['order_status']==2){//..结算订单
            $order_id = 0;
            if ($order){//..存在则改变订单状态,并且订单只能是付款状态
                $re_count = false;
                if ($order['order_status']==1){
                    unset($updata['uid']);//防止找回订单没浏览记录的情况
                    $re_count = db('Orders')->where('id',$order['id'])->update($updata);
                    $order_id = $order['id'];
                }
            }else {//..反之导入
                $re_count = db('Orders')->insertGetId($updata);//返回主键
                $order_id = $re_count;
                //首次导入订单，绑定砍价
                if ($kanjia_info){
                    $kanjia_info->order_id = $order_id;
                    $kanjia_info->save();
                }elseif ($miandan_info){
                    $miandan_info->order_id = $order_id;
                    $miandan_info->save();
                }
            }
            if ($re_count){
                if ($kanjia_info || $order['is_kanjia']==1){//如果是砍价订单，砍价处理
                    //发放砍价订单奖励，非立即发放
                    trace('***砍价订单***');
                }elseif ($miandan_info || $order['is_miandan']==1){//如果是免单订单，免单处理
                    //发放免单订单奖励，立即发放          设置金额乘以分成比例
                    trace('***免单订单***');
                    //设置金额，当前最新的
                    //$set_money = db('goods_miandan')->where('item_id',$updata['item_id'])->value('return_money');
                    //改为以前存入的
                    $set_money = $miandan_info->return_money;
                    //可得到钱
                    $get_money = $set_money*$updata['share_rate']/100;
                    //给钱
                    add_money('miandan', $uid,['money'=>$get_money,'remark'=>'免单返还:'.$updata['trade_no'],'attach'=>$order_id]);
                    //更新免单订单
                    $miandan_info->is_used = 1;
                    $miandan_info->return_money_real = $get_money;
                    $miandan_info->order_id = $order_id;
                    $miandan_info->save();
                    //分佣
                    miandan_fenyong($uid, $set_money);
                }else {
                    //升级并星火奖励
                    user_exp_add($uid,$updata, $order_id);
                    //...首单奖励
                    shoudan($uid,$updata);
                    //...代理无限代提成
                    agent_commission($uid, $updata, $order_id);
                    
                    //订单金额大于10元且淘宝佣金大于0.1元的普通订单均返还一个免单券
                    $lvcfg = get_db_config(true)['user_leval_cfg'];
                    $price1 = floatval($lvcfg['miandan']['order_quan_price']);
                    $price2 = floatval($lvcfg['miandan']['order_quan_yjprice']);
                    if ($price1>0 && $price2>0){
                        if ($updata['pay_fee']>$price1 && $updata['rj_price'] > $price2 ){
                            miandan_quan_logs($uid, 3);
                        }
                    }
                }
                
            }
            
        }
        echo 'ok';
        //dump($data);
        //dump($updata);
    }
    /**
     * 订单明细-第三方服务商推广
     */
    public function third()
    {
        $this->tbktg(1);
    }
    /**
     * 淘宝客维权退款 
     */
    public function tbk_refund($type=0){
        $data = file_get_contents('php://input');trace($data);
        //$data = '["138035502781521073","138035502781521073","常家男装张大妈烧饼2","11","1.65","维权成功","2018-03-19 20:41:27","2018-03-21 16:26:47","2018-03-21 16:36:38"]';
        $data = json_decode($data,true);
        if (!is_array($data)) exit('error');
        //数据转换--begin
        $keys = [
            'trade_no','trade_no_son','title','refund_fee','return_fee','status','js_time','refund_create_time','refund_finish_time'
        ];
        //数据类型转换
        $updata = array_combine($keys, $data);
        $status_text2int = ['维权成功'=>1,'维权创建'=>0];
        $updata['status'] = $status_text2int[$updata['status']];
        //trace($updata);
        //只有维权成功的时候才操作
        if ($updata['status']==1){
            //如果没有这条记录
            $refund = model('OrdersRefund')->get(['trade_no_son'=>$updata['trade_no_son']]) ?? [];
            if (count($refund)==0){
                if(model('OrdersRefund')->save($updata)){
                    //改变订单状态,精确到子订单，核对支付金额和佣金和结算时间去掉结算时间'js_time'=>$updata['js_time']
                    $order = model('Orders')->get(['trade_no'=>$updata['trade_no'],'pay_fee'=>$updata['refund_fee'],'ygsr'=>$updata['return_fee']]);
                    //如果订单被删除则不处理,add
                    if ($order && $order['status']!=1){
                        trace('订单被删除');
                        exit('ok');
                    }
                    if ($order && $order['order_status']!=5){//不是已经退过的订单
                        $order_status = $order['order_status'];
                        $order->order_status = 5;
                        $order->save();
                        //砍价订单退款
                        if ($order['uid']>0  && $order_status==2 && $order['is_kanjia']==1 && $order['is_kanjia_fanli']==1){
                            //所有得到本单的人
                            $get_list = db('kanjia_money_logs')->where('type','in','goods_fanli')->where('attach',$order['id'])->where('money','>',0)->select();
                            if ($get_list){
                                foreach ($get_list as $k=>$v){
                                    //退钱
                                    add_kanjia_money('goods_fanli_refund', $v['uid'],['money'=>-$v['money'],'remark'=>'订单退款:'.$order['trade_no'],'attach'=>$order['id']]);
                                }
                            }
                        }
                        //如果是有头有主的订单，并且是已经结算的订单，否则只到上一步改变下状态,新增不是砍价订单
                        if ($order['uid']>0  && $order_status==2 && $order['is_kanjia']==0){
                            //1.如果是首单退回首单上级奖励
                            //查询结算订单还有几笔
                            $js_count = db('Orders')->where('uid',$order['uid'])->where('order_status',2)->count();
                            if ($js_count==0){
                                //begin...
                                $sdlogs = model('ShoudanLogs')->all(['uid'=>$order['uid'],'status'=>1]);
                                foreach ($sdlogs as $k=>$v){
                                    $v->status = 0;
                                    $v->save();
                                    db('User')->where('uid',$v['pid'])->setDec('sd_money',$v['money']);
                                }
                                
                            }
                            //2.如果会员降级，退回上级奖励
                            $uinfo = model('User')->get(['uid'=>$order['uid']]);
                            $exp = $uinfo['experience']-$order['pay_fee'];//重新计算的经验值
                            $lvcfg = get_db_config(true)['user_leval_cfg'];
                            if ($exp < $lvcfg[1]['sjtj']){
                                $lv = 0;
                            }elseif ($exp >= $lvcfg[1]['sjtj'] && $exp < $lvcfg[2]['sjtj'] ){
                                $lv = 1;
                            }elseif ($exp >= $lvcfg[2]['sjtj'] && $exp < $lvcfg[3]['sjtj']){
                                $lv = 2;
                            }elseif ($exp >= $lvcfg[3]['sjtj']){
                                $lv = 3;
                            }
                            //如果会员降级 
                            if ($lv < $uinfo->getData('leval')){
                                //如果本身为代理则不降级，只扣经验值
                                if ($uinfo->getData('leval')>3){
                                    db('User')->where('uid',$uinfo['uid'])->setDec('experience',$order['pay_fee']);
                                }else {
                                    //要看是降几级
                                    for ($i=$lv;$i<$uinfo->getData('leval');$i++){
                                        $refund_lv = $i+1;
                                        $xhlogs = model('XhLogs')->all(['uid'=>$order['uid'],'status'=>1,'leval'=>$refund_lv]);
                                        foreach ($xhlogs as $k=>$v){
                                            $v->status = 0;
                                            $v->save();
                                            //退钱
                                            add_money('xinghuo_refund', $v['pid'],['money'=>-$v['money'],'remark'=>'下级会员降级为:'.config('site.user_leval')[$refund_lv]]);
                                        }
                                    }
                                    //降级
                                    $uinfo->experience = $exp;
                                    $uinfo->leval = $lv;
                                    $uinfo->save();
                                    //5.扣掉新加的额外10元奖励,必须是从钻石降到其它等级
                                    if ($uinfo->getData('leval')>=3){
                                        //找到得钱记录,因为只会有一个人得到，所以只查最新得到的那个人
                                        $ew_log = db('money_logs')->where('type','agent_fans_up3_ewjl')->where('attach',$uinfo['uid'])->order('id desc')->find();
                                        if ($ew_log){
                                            add_money('agent_fans_up3_ewjl_refund', $ew_log['uid'],['money'=>-$ew_log['money'],'remark'=>'下级会员降级为:'.config('site.user_leval')[$lv],'attach'=>$uinfo['uid']]);
                                        }
                                    }
                                }
                            }
                            //3.退回代理的业绩提成,没有条件直接把记录里的全部退回
                            $commi_logs = model('CommiLogs')->all(['order_id'=>$order['id'],'status'=>1]);
                            foreach ($commi_logs as $k=>$v){
                                $v->status = 0;
                                $v->save();
                                //退钱
                                add_money('agent_wxtc_refund', $v['uid'],['money'=>-$v['money'],'remark'=>'订单退款，业绩扣除']);
                            }
                            //4.退回自购还返
                            //所有得到本单的人
                            $get_list = db('money_logs')->where('type','in','fanli,fanli3,tuandui_gwfl')->where('money','>',0)->where('attach',$order['id'])->select();
                            if ($get_list){
                                foreach ($get_list as $k=>$v){
                                    //退钱
                                    add_money('fanli_refund', $v['uid'],['money'=>-$v['money'],'remark'=>'订单退款:'.$order['trade_no'],'attach'=>$order['id']]);
                                }
                            }
                            
                            
                        }
                    }
                    
                }
            }
        }
        
        
        echo 'ok';
    }
    /**
     * 第三方服务商维权退款
     */
    public function tbk_refund3(){
        
        $this->tbk_refund(1);
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
